sort-on

 

sort-on allows you to sort the agents in an agentset based on some user-chosen agent variable or even an arbitrary reporter. For example, if you wanted to get a list of turtles sorted by their xcor, you could use sort-on [xcor] turtles, or if you wanted to get a list of patches sorted by the value of their patch variable "pollution", you could use sort-on [pollution] patches.

The exact syntax is sort-on <reporter> <agentset>. Note that while in the prior examples, the reporter was just a simple variable in square braces, they can be arbitrarily involved code. For example, say we wanted to sort turtles based on how close their x-coordinate was to 0, we could use sort on [abs xcor] turtles which would get the absolute value of the xcor before passing into the sorting algorithm.

Note that the output of sort-on is always a newly created list -- it does not modify the original list at all. It also, like sort sorts in ascending order, so if you want the results in descending order, you can pass the output into reverse.

 

Try it Yourself

 
 
 
 
 
 
 

What's next?

Once you mastered the sort-on primitive, don't stop there. Check out the resources below to improve your NetLogo skills.

 
Similar primitives:
sort-by

sort a list based on a user-defined comparison reporter

Read more
count

Count the number of agents in an agentset.

Read more
mean

Find the mean of a list of values.

Read more
 
Learn another primitive